import React, { Component } from 'react'
import {connect} from "react-redux"
import * as action from "../action"
import {bindActionCreators} from "redux"
let checkitem = []
class Shopcar extends Component {
    addnum (id) { // 购物车++方法
        this.props.addNum(id) // 1.this.props.action里的方法
    }
    del (id) {
        this.props.delfn(id)
    }
    cheekLL () { // 全选的事件
      this.props.checkAll() // 三步走得第一步
    }
    cheekItem(id) { // 点击购物车列表里每一个商品得选中与不选中事件
       this.props.checkitem(id)
    }
    componentWillUnmount() { // 组件销毁前的生命周期
        console.log("componentWillUnmount",checkitem);
        checkitem.forEach((item,index)=>{
            item.status = "未发货"
        })
        this.props.orderfn(checkitem)
    }
   render() {  // 当仓库里的数据发生变化，就会触发render函数执行
    // console.log("render")
    checkitem = this.props.shopArr.filter((item,index)=>{ 
        return item.flag // 在购物车页面选中得数据
    }) 

    console.log(checkitem,"checkitem");
    let addnum = checkitem.reduce((a,b)=>{
        return a +  b.price * b.number
    },0)
    return (
      <div>
          {
              this.props.shopArr && this.props.shopArr.length ?  this.props.shopArr.map((item,index)=>{
                  return <div key={index}>
                      <img src={item.img} alt="" />
                      <span>价格：{item.price}</span>
                      <span>标题：{item.title}</span>
                      <h4><input type="checkbox"  checked={item.flag || ""} onChange={this.cheekItem.bind(this,item.id)}/><button onClick={this.del.bind(this,item.id)} style={{marginLeft:"25px"}}>--</button><b>{item.number}</b> <button onClick={this.addnum.bind(this,item.id)}>++</button></h4>
                  </div>
              }):"购物车空空"
          }
          <div>
              <span>全选：</span><input type="checkbox" checked={this.props.checkall} onChange={this.cheekLL.bind(this)}/>
              <span>总价：{addnum}</span>
          </div>
      </div>
    )
  }
}
const mapStateToProps = (state) => {
    return {
        ...state.shopReducer
    }
}

const mapDispatchToProps =  (dispatch)=>bindActionCreators(action,dispatch)
export default connect(mapStateToProps,mapDispatchToProps)(Shopcar)